#include "template_set.h"
#include "ship_template.h"
#include "slot_template.h"
#include "json/value.h"

using namespace std;

TemplateSet::TemplateSet(string _name) : name(_name) {}

TemplateSet::TemplateSet(const Json::Value & _set, string _name) {
	name = _set["Name"].asString();
	for ( unsigned int i = 0; i < _set["ShipTemplates"].size(); i++ )
		shipTemplates.emplace_back(_set["ShipTemplates"][i]);

	if ( _name != "" ) name = _name;	
}

Json::Value TemplateSet::convertToJson() const {
		Json::Value set;

		set["Name"] = name;
		set["Type"] = "TemplateSet";

		unsigned int i = 0;

		for ( auto &it : shipTemplates ) {
			set["ShipTemplates"][i] = it.convertToJson();
			i++;
		}

		return set;
}

void TemplateSet::addShipTemplate( const ShipTemplate & _shipTemplate ) {
	shipTemplates.emplace_back( _shipTemplate );
}

void TemplateSet::addShipTemplate( const Json::Value & _shipTemplate, string _name ) {
	shipTemplates.emplace_back( _shipTemplate,_name );
}

void TemplateSet::rmShipTemplate( int _shipTemplate ) {
	if ( _shipTemplate < 0 ) throw invalid_argument("TemplateSet::rmShipTemplate(int)");
	auto it = shipTemplates.begin();
	advance(it, _shipTemplate);

	shipTemplates.erase(it);
}

void TemplateSet::replShipTemplate( int _shipTemplate, const ShipTemplate & _newShipTemplate ) {
	if ( _shipTemplate < 0 ) throw invalid_argument("TemplateSet::replShipTemplate(int)");
	auto it = shipTemplates.begin();
	advance(it, _shipTemplate);
	
	it = shipTemplates.erase(it);
	shipTemplates.emplace(it, _newShipTemplate);
}

void TemplateSet::renameShipTemplate(int _shipTemplate, string _name) {
	if ( _shipTemplate < 0 ) throw invalid_argument("TemplateSet::renameShipTemplate(int)");
	auto it = shipTemplates.begin();
	advance(it, _shipTemplate);

	(*it).name = _name;
}

const ShipTemplate * TemplateSet::getShipTemplate( int _shipTemplate ) const {
	if ( _shipTemplate < 0 ) throw invalid_argument("TemplateSet::getShipTemplate(int)");
	auto it = shipTemplates.begin();
	advance(it, _shipTemplate);

	const ShipTemplate * pointer = & (*it);
	return pointer;
}

int TemplateSet::getShipTemplatesNumber() const {
	return shipTemplates.size();
}

vector<array<string,3>> TemplateSet::getShipTemplateSummaries() const {
	vector<array<string,3>> summaries;

	for ( auto &it : shipTemplates )
		summaries.push_back( it.getSummary() );

	return summaries;
}

vector<string> TemplateSet::getShipTemplateNames() const {
	vector<string> names;

	for ( auto &it : shipTemplates )
		names.push_back( it.name );

	return names;
}
